package com.chexiehui.jc.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.List;

import se.emilsjolander.stickylistheaders.StickyListHeadersAdapter;

public abstract class CommonStickyListHeaderAdapter<T extends IStickItem> extends BaseAdapter implements StickyListHeadersAdapter {
    protected Context mContext;
    protected List<T> mDatas;
    protected int mHeadLayoutId;
    protected int mItemLayoutId;

    public CommonStickyListHeaderAdapter(Context context, int headLayoutId, int itemLayoutId, List<T> datas) {
        this.mContext = context;
        this.mDatas = datas;
        this.mHeadLayoutId = headLayoutId;
        this.mItemLayoutId = itemLayoutId;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        CommonAbsViewHolder viewHolder = null;
        if (convertView == null) {
            View itemView = LayoutInflater.from(mContext).inflate(mItemLayoutId, parent, false);
            viewHolder = new CommonAbsViewHolder(mContext, itemView, parent, mItemLayoutId, position);
        } else {
            viewHolder = (CommonAbsViewHolder) convertView.getTag();
            viewHolder.setPosition(position);
        }
        convertItem(viewHolder, getItem(position), position);
        return viewHolder.getConvertView();
    }

    protected abstract void convertItem(CommonAbsViewHolder viewHolder, T item, int position);

    protected abstract void convertHead(CommonAbsViewHolder viewHolder, T item, int position);

    @Override
    public int getCount() {
        return mDatas.size();
    }

    @Override
    public T getItem(int position) {
        return mDatas.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getHeaderView(int position, View convertView, ViewGroup parent) {
        CommonAbsViewHolder viewHolder = null;
        if (convertView == null) {
            View itemView = LayoutInflater.from(mContext).inflate(mHeadLayoutId, parent, false);
            viewHolder = new CommonAbsViewHolder(mContext, itemView, parent, mHeadLayoutId, position);
        } else {
            viewHolder = (CommonAbsViewHolder) convertView.getTag();
            viewHolder.setPosition(position);
        }
        convertHead(viewHolder, getItem(position), position);
        return viewHolder.getConvertView();
    }

    @Override
    public long getHeaderId(int position) {
        return mDatas.get(position).getItemHeadId();
    }
}
